import React, { Component } from 'react';
import { Cascader } from 'antd';
import PropTypes from 'prop-types';
import MapJson from '@util/province-city-area.js';

const _provinceCityArea = [];
const _provinceCity = [];
const _province = [];

MapJson.forEach(item => {
  const _pcaChildren = [];
  const _pcChildren = [];
  item.children
    .filter(item => item.name !== '市辖区')
    .map(item => {
      const tempC = {
        value: item.name,
        label: item.name
      };

      if (item.children) {
        tempC.children = item.children
          .filter(item => item.name !== '市辖区')
          .map(item => ({
            value: item.name,
            label: item.name
          }));
        if (tempC.children.length === 0) {
          delete tempC.children;
        }
      }

      _pcaChildren.push(tempC);

      _pcChildren.push({
        value: item.name,
        label: item.name
      });
    });

  _province.push({
    value: item.name,
    label: item.name
  });
  _provinceCity.push({
    value: item.name,
    label: item.name,
    children: _pcChildren
  });
  _provinceCityArea.push({
    value: item.name,
    label: item.name,
    children: _pcaChildren
  });
});

const provinceCityAreaMaps = [_province, _provinceCity, _provinceCityArea];

class RegionSelect extends Component {
  render() {
    const {
      onChange,
      value = {},
      changeOnSelect = true,
      className,
      allowClear = true,
      mapLevel = 2,
      popupClassName
    } = this.props;
    const { province, city, area } = value;
    const options = provinceCityAreaMaps[mapLevel];

    const onValueChange = value => {
      onChange({ province: value[0], city: value[1], area: value[2] });
    };
    return (
      <Cascader
        className={className}
        allowClear={allowClear}
        popupClassName={popupClassName}
        value={[province, city, area]}
        options={options}
        changeOnSelect={changeOnSelect}
        onChange={onValueChange}
        expandTrigger="hover"
        style={{ width: '100%', flex: 1 }}
        placeholder="请输入你所在的地址名称"
      />
    );
  }
}

RegionSelect.propTypes = {
  province: PropTypes.string,
  city: PropTypes.string,
  onChange: PropTypes.func,
  value: PropTypes.object,
  forForm: PropTypes.bool,
  className: PropTypes.string,
  allowClear: PropTypes.boolean,
  changeOnSelect: PropTypes.boolean,
  popupClassName: PropTypes.string,
  mapLevel: PropTypes.number
};

RegionSelect.defaultProps = {
  // eslint-disable-next-line no-undefined
  city: undefined
};

const validateRegionSelect = (rule, value, callback) => {
  if (!value || !value.province || !value.city) {
    callback('请选择单位所在地');
  } else {
    callback();
  }
};

export { validateRegionSelect };
export default RegionSelect;
